package at.fhooe.SRWCProject.WiFiDirect.Socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
import at.fhooe.SRWCProject.Bluetooth.ChatActivity;
import at.fhooe.SRWCProject.MainActivity;

public class ConnectThread extends Thread {
	/**
	 * 
	 */
	private final Context mainActivity;
	private Socket socket;
	private final String mmAddress;
	private final Handler mmHandler;

	private int timeout = 10000;

	public ConnectThread(Context mainActivity, String address, Handler handler) {
		this.mainActivity = mainActivity;
		mmAddress = address.substring(1);
		mmHandler = handler;
		Toast.makeText(this.mainActivity, mmAddress, Toast.LENGTH_SHORT)
				.show();
		socket = new Socket();
		try {
			socket.bind(null);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			InetSocketAddress socketAddress = new InetSocketAddress(
					mmAddress, MainActivity.PORT);
			socket.connect(socketAddress, timeout);
			ConnectionThread conn = new ConnectionThread(socket, mmHandler);
			mmHandler.obtainMessage(MainActivity.SOCKET_CONNECTED, conn).sendToTarget();
			conn.start();
		} catch (IOException e) {
			try {
				socket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
}